package com.example.projectmanagement.controller.study;

import com.example.projectmanagement.dto.study.AchievementDto;
import com.example.projectmanagement.model.study.Achievement;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.service.study.AchievementService;
import com.example.projectmanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/study/achievements")
@CrossOrigin
public class AchievementController {

    @Autowired
    private AchievementService achievementService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取用户的所有成就
     */
    @GetMapping
    public ResponseEntity<List<AchievementDto>> getUserAchievements() {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        List<Achievement> achievements = achievementService.getUserAchievements(userOpt.get());
        List<AchievementDto> achievementDtos = achievements.stream()
                .map(this::convertToAchievementDto)
                .collect(Collectors.toList());
        
        return ResponseEntity.ok(achievementDtos);
    }

    /**
     * 获取用户的成就（分页）
     */
    @GetMapping("/page")
    public ResponseEntity<Page<Achievement>> getUserAchievements(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        Pageable pageable = PageRequest.of(page, size);
        Page<Achievement> achievements = achievementService.getUserAchievements(userOpt.get(), pageable);
        return ResponseEntity.ok(achievements);
    }

    /**
     * 获取用户特定类型的成就
     */
    @GetMapping("/type/{achievementType}")
    public ResponseEntity<List<AchievementDto>> getUserAchievementsByType(@PathVariable String achievementType) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        List<Achievement> achievements = achievementService.getUserAchievementsByType(userOpt.get(), achievementType);
        List<AchievementDto> achievementDtos = achievements.stream()
                .map(this::convertToAchievementDto)
                .collect(Collectors.toList());
        
        return ResponseEntity.ok(achievementDtos);
    }

    /**
     * 解锁学习类成就
     */
    @PostMapping("/unlock/study")
    public ResponseEntity<Achievement> unlockStudyAchievement(@RequestParam String achievementName) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Achievement achievement = achievementService.unlockStudyAchievement(userOpt.get(), achievementName);
            return ResponseEntity.ok(achievement);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 解锁互动类成就
     */
    @PostMapping("/unlock/interaction")
    public ResponseEntity<Achievement> unlockInteractionAchievement(@RequestParam String achievementName) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Achievement achievement = achievementService.unlockInteractionAchievement(userOpt.get(), achievementName);
            return ResponseEntity.ok(achievement);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 解锁里程碑类成就
     */
    @PostMapping("/unlock/milestone")
    public ResponseEntity<Achievement> unlockMilestoneAchievement(@RequestParam String achievementName) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        try {
            Achievement achievement = achievementService.unlockMilestoneAchievement(userOpt.get(), achievementName);
            return ResponseEntity.ok(achievement);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取当前认证用户的ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            return userService.getUserByUsername(username).map(User::getId).orElse(null);
        }
        return null;
    }

    /**
     * 转换Achievement到AchievementDto
     */
    private AchievementDto convertToAchievementDto(Achievement achievement) {
        AchievementDto dto = new AchievementDto();
        dto.setId(achievement.getId());
        if (achievement.getUser() != null) {
            dto.setUserId(achievement.getUser().getId());
            dto.setUserName(achievement.getUser().getName());
        }
        dto.setAchievementName(achievement.getAchievementName());
        dto.setAchievementType(achievement.getAchievementType());
        dto.setDescription(achievement.getDescription());
        dto.setBadgeIcon(achievement.getBadgeIcon());
        dto.setEarnedTime(achievement.getEarnedTime());
        return dto;
    }
}